<template>
  <div class="bg-white dark:bg-zinc-900 sticky top-0 left-0 z-10 duration-500">
    <ul
      ref="ulTarget"
      class="relative flex overflow-x-auto p-1 text-xs text-zinc-600 overflow-hidden"
    >
      <!-- 滑块 -->
      <li
        ref="sliderTarget"
        :style="sliderStyle"
        class="absolute h-[22px] dark:bg-zinc-800 bg-zinc-900 rounded-lg duration-200"
      ></li>
      <!-- 汉堡按钮 -->
      <!-- <li class="z-20 fixed top-0 right-[-1px] h-4 px-1 flex items-center bg-white shadow-l-white" @click="isOpenPopup = !isOpenPopup"> -->
      <li
        class="z-20 fixed top-0 right-[-1px] h-4 px-1 flex items-center bg-white dark:bg-zinc-900 shadow-l-white dark:shadow-l-zinc"
        @click="onShowPopup()"
      >
        <m-svg-icon class="w-1.5 h-1.5" name="hamburger"></m-svg-icon>
      </li>
      <!-- items -->
      <li
        v-for="(item, index) in $store.getters.categorys"
        :key="item.id"
        class="shrink-0 px-1.5 py-0.5 z-10 duration-200 last:mr-4"
        :class="{
          'text-zinc-100': currentCategoryIndex === index
        }"
        @click="onItemClick(index)"
        :ref="setItemRef"
      >
        {{ item.name }}
      </li>
    </ul>

    <m-popup v-model="isVisable">
      <menu-vue @onItemClick="onItemClick"></menu-vue>
    </m-popup>
  </div>
</template>
<script setup>
import { ref, onBeforeUpdate, watch } from 'vue'
import { useScroll } from '@vueuse/core'
import MenuVue from '../../../components/menu/index.vue'
// import MenuVue from "@/views/"
// const props = defineProps({
//     data: {type: Array, required: true}
// })
const sliderStyle = ref({
  transform: 'translateX(0px)',
  width: '52px'
})
const currentCategoryIndex = ref(0)
let itemRefs = []
const setItemRef = (el) => {
  if (el) {
    itemRefs.push(el)
  }
}
onBeforeUpdate(() => {
  itemRefs = []
})
const ulTarget = ref(null)
const { x: ulTargetLeft } = useScroll(ulTarget)

watch(currentCategoryIndex, (val) => {
  const { left, width } = itemRefs[val].getBoundingClientRect()
  sliderStyle.value = {
    transform: `translateX(${ulTargetLeft.value + left - 10 + 'px'})`,
    width: width + 'px'
  }
})
const onItemClick = (index) => {
  currentCategoryIndex.value = index
  isOpenPopup.value = false
  isVisable.value = false
}

const isOpenPopup = ref(false)
const isVisable = ref(false)
const onShowPopup = () => {
  isVisable.value = true
}
</script>
